// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
use serde::Serialize;
use std::process::Command;
use tauri::Error;

#[derive(Serialize)]
struct CommandResult {
    code: Option<i32>,
    stdout: Option<String>,
    stderr: Option<String>,
}

#[tauri::command]
fn execute_command(program: &str, args: Vec<&str>) -> Result<CommandResult, Error> {
    let output = Command::new(program).args(&args).output()?;
    if output.status.success() {
        return Ok(CommandResult {
            code: output.status.code(),
            stdout: Some(String::from_utf8_lossy(&output.stdout).to_string()),
            stderr: None,
        });
    }
    Ok(CommandResult {
        code: output.status.code(),
        stdout: None,
        stderr: Some(String::from_utf8_lossy(&output.stderr).to_string()),
    })
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_shell::init())
        .invoke_handler(tauri::generate_handler![execute_command])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
